﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Xml;
using AMS.Inventory.DataAccess;
using AMS.Inventory.Entities;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Entities;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using VitCode.Web.UI;

namespace AMSInventoryWeb.BaseData
{
    public partial class BatchPlanCreator : Page
    {
        private const string OBJ_ID = "Id";
        private const string PLAN_KEY_VALS = "PlanKeyVals";
        private readonly CreateControlHelper m_CreateCtlHlp = new CreateControlHelper();
        private PageBuilder m_PageBuilder;
        private BaseDataAccess m_Acc = new BaseDataAccess();
        public string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml"; }
        }

        private UserDataSourceBuilder DataSourceBuilder
        {
            get { return (UserDataSourceBuilder)Session["DataSourceBuilder"]; }
            set { Session["DataSourceBuilder"] = value; }
        }

        private string MenuId
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("MenuId", this); }
        }

        public StringCollection KeyVals
        {
            get { return ((StringCollection)Session[PLAN_KEY_VALS]); }
            set { Session[PLAN_KEY_VALS] = value; }
        }


        private string QueryCondition
        {
            get
            {
                if (ViewState["QueryCondition"] != null)
                    return ViewState["QueryCondition"].ToString();
                else
                    return "";
            }
            set { ViewState["QueryCondition"] = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(this, SettingXmlPath);
            ucPrincipal.ObjClassName = typeof(User).Name;
            ucPrincipal.ObjKeyProName = "Id";
            ucPrincipal.ObjShowProName = "Name";
            ucPrincipal.InitCurrUser = "true";
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            pgList.DataSourceBuilderDelegate = new PaginationGrid.GridDataSourceBuilderDelegate(BindPgList);
            if (!IsPostBack)
            {
                PagePermissionHelper.CheckIsLoginToDefault(this);
                m_CreateCtlHlp.SetDdlCondition(pgList, ddlCondition,10);
                m_CreateCtlHlp.SetDdlCondition(pgList, ddlGroupPro,10);
            }
        }

        private PaginationGridDataSourceBuilder BindPgList()
        {
            string sql =
                "SELECT [Id] ,[Barcode] ,[Name] ,[ModelNumber] ,[UnitInfo]  "+
      ",[TypeName] ,[AssetTypeInfo] ,[NatureInfo] ,[SiteInfo] ,[Location]  ,[DepartmentInfo] ,[SourceInfo]  " +
      ",[Manufacturers] ,[Supplier]  FROM [v_PlanSelectAssetList] o ";
            sql += " " + QueryCondition;
            var dt = m_Acc.GetDataTableBySql(sql);
            btnCreate.Enabled = dt != null && dt.Rows.Count > 0;
            DataSourceBuilder = new UserDataSourceBuilder(sql, pgList);
            
            return DataSourceBuilder;
        }

        protected void ConditionSelector1_SelectCondition(SelectConditionEventArgs e)
        {
            QueryCondition = null;
            if (ConditionSelector1.SelectedConditionString.Length > 0)
                QueryCondition = " where " + ConditionSelector1.SelectedConditionString;
            pgList.BindGrid();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            pgList.BindGrid();
        }



        protected void pgList_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
            string strUrlVal = ("/BaseData/ObjEdit.aspx?MenuId=" + MenuId + "&ClassName=" + typeof(LedgerInfo).Name +
                                "&Id=" + e.SelectedDataKeyValue);
            m_PageBuilder.ShowModalDialog(strUrlVal, Page, typeof(LedgerInfo).Name, "");
        }

        private PlanInfo SavePlanInfo(string planName, User principal)
        {
            PlanInfo obj = new PlanInfo();
            obj.CreateDate = DateTime.Now;
            obj.Name = planName;
            if (ucStartDate.Text.Length > 0)
                obj.StartDate = Convert.ToDateTime(ucStartDate.Text);
            if (ucEndDate.Text.Length > 0)
                obj.FinishDate = Convert.ToDateTime(ucEndDate.Text);
            obj.Responsible = principal;
            return obj;
        }

        public bool IsExists(PlanInfo objPlan, BaseDataAccess acc)
        {
            IList ilObjs = acc.Session.CreateQuery("Select count(*) from " + typeof(PlanInfo).Name + " o Where o.Id<>'" + objPlan.Id.ToString() + "' and o.Name='" + objPlan.Name + "'").List();
            if (ilObjs != null && ilObjs.Count > 0)
            {
                int amount = Convert.ToInt32(ilObjs[0]);
                if (amount > 0)
                    return true;
            }
            return false;
        }

        private void CreatePlans(ref StringBuilder sbErrMsg)
        {
            string strTableName = "AmsInventory_LedgerInfo";
            int maxAssetAmount = Convert.ToInt32(txtMaxOnePlanAmount.Text);
            string strGroupByName = ddlGroupPro.SelectedValue;
            string strSql = "Select "+strGroupByName+" From "+strTableName+" Group by " + strGroupByName;
            SqlHelper sqlHelper = new SqlHelper();
            BaseDataAccess acc = new BaseDataAccess();
            DataTable dt = sqlHelper.GetDataTable(strSql, acc);
            if (dt == null)
                return;
            var ndPlanInfos = new NameObjectDictionary();
            var ndPlanNameAssetInfos = new NameObjectDictionary();
            var ndLedgerInfos = acc.GetObjectsByKeyValues(typeof(LedgerInfo).Name, OBJ_ID, DataSourceBuilder.PrimaryKeys);
            var objPrincipal = acc.GetSingleObjectById(typeof(User).Name, ucPrincipal.ObjKeyProVal.ToString());
            foreach (DataRow dr in dt.Rows)
            {
                string strGroupByValue = Convert.ToString(dr[0]);
                bool flag = true;
                int planAmount = 0;
                if(flag)
                {
                    string strFirstPlanName = txtPlanHeadString.Text + "_" + strGroupByName + "_" + strGroupByValue;
                    strSql = "select Count(*) from (Select ia.Id From " + strTableName + " ia Where  " + strGroupByName + "='" + strGroupByValue + "') a";
                    strSql += " left join (select i.BaseObjectId,p.Name from dbo.AmsInventory_InventoryInfo i" +
                              " inner join dbo.AmsInventory_PlanInfo p on p.Id=i.PlanId" +
                              " where p.Name = '"+strFirstPlanName+"' or p.Name like '"+strFirstPlanName+"[_]EX[_]%') b on a.Id=b.BaseObjectId where b.BaseObjectId is null";
                    object objVal = sqlHelper.ExecuteScalar(acc.Session,strSql);
                    if (objVal == null && objVal is int && ((int)objVal) == 0)
                        break;

                    planAmount++;
                    PlanInfo plan = new PlanInfo();
                    if(planAmount==1)
                    {
                        plan.Name = strFirstPlanName;;
                    }
                    else
                    {
                        plan.Name = plan.Name + "_EX_" + planAmount;
                    }
                    
                    if (IsExists(plan,acc))
                    {
                        sbErrMsg.Append("【" + plan.Name + "】计划名称已经存在，不能保存\r\n");
                        continue;
                    }
                    plan.CreateDate = DateTime.Now;
                    plan.StartDate = plan.StartDate;
                    plan.FinishDate = plan.FinishDate;
                    plan.Memo = plan.Memo;
                    plan.Responsible = plan.Responsible;
                    plan.MaxAssetAmount = maxAssetAmount;
                    acc.SaveOrUpdate(plan);
                    Guid planId = plan.Id;

                    
                    
                }
                
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            var acc = new CoreDataAccess();
            var sbErrInfo = new StringBuilder();
            ucPrincipal.BackColor = Color.Transparent;
            ucEndDate.BackColor = Color.Transparent;
            ucStartDate.BackColor = Color.Transparent;
            txtMaxOnePlanAmount.BackColor = Color.Transparent;
            if (ucPrincipal.ObjShowProVal == null || ucPrincipal.ObjShowProVal.ToString().Length==0)
            {
                sbErrInfo.Append("【负责人】不能为空\r\n");
                ucPrincipal.BackColor = Color.Yellow;
            }
            if (ucStartDate.Text.Length == 0)
            {
                sbErrInfo.Append("【开始时间】不能为空\r\n");
                ucStartDate.BackColor = Color.Yellow;
            }
            if (ucEndDate.Text.Length == 0)
            {
                sbErrInfo.Append("【结束时间】不能为空\r\n");
                ucEndDate.BackColor = Color.Yellow;
            }
            if (txtMaxOnePlanAmount.Text.Length == 0)
            {
                sbErrInfo.Append("【单计划最大资产量】不能为空\r\n");
                txtMaxOnePlanAmount.BackColor = Color.Yellow;
            }
            else
            {
                Regex reg = new Regex("\\d+$");
                if (!reg.IsMatch(txtMaxOnePlanAmount.Text))
                {
                    sbErrInfo.Append("【单计划最大资产量】必需是大于0的整数\r\n");
                    txtMaxOnePlanAmount.BackColor = Color.Yellow;
                }
                else
                {
                    var iMaxCount = Convert.ToInt32(txtMaxOnePlanAmount.Text);
                    if (iMaxCount <= 0)
                    {
                        sbErrInfo.Append("【單計畫最大資產量】必需是大於0的整數\r\n");
                        txtMaxOnePlanAmount.BackColor = Color.Yellow;
                    }
                }
            }

            if(sbErrInfo.Length>0)
            {
                Alert.MessageBox(sbErrInfo.ToString());
                return;
            }

            int maxAssetAmount = Convert.ToInt32(txtMaxOnePlanAmount.Text);
            acc.BeginTransaction();
            try
            {
                
                var ndPlanInfos = new NameObjectDictionary();
                var ndPlanNameAssetInfos = new NameObjectDictionary();
                var ndLedgerInfos = acc.GetObjectsByKeyValues(typeof(LedgerInfo).Name, OBJ_ID, DataSourceBuilder.PrimaryKeys);
                var objPrincipal = acc.GetSingleObjectById(typeof(User).Name, ucPrincipal.ObjKeyProVal.ToString());
                foreach (LedgerInfo obj in ndLedgerInfos.Values)
                {
                    var strProMemo = ddlGroupPro.SelectedItem.Text;
                    var strProName = ddlGroupPro.SelectedValue;
                    var pi = obj.GetType().GetProperty(strProName);
                    if (pi == null)
                        throw new ArgumentException(strProMemo + "不是有效的属性,请重新设定");
                    object objProVal = pi.GetValue(obj, null) ?? "";
                    string strPlanName = txtPlanHeadString.Text + "_" + strProMemo + "_" + objProVal;
                    if (!ndPlanInfos.Contains(strPlanName))
                    {
                        if (objPrincipal != null && objPrincipal is User)
                        {
                            var tempPlan = SavePlanInfo(strPlanName, ((User)objPrincipal));
                            ndPlanInfos[strPlanName] = tempPlan;
                            ndPlanNameAssetInfos[strPlanName] = new ArrayList();
                        }
                    }
                    var ivObj = new InventoryInfo();
                    ivObj.SetProByLedgerInfo(obj);
                    ((ArrayList)ndPlanNameAssetInfos[strPlanName]).Add(ivObj);
                }
                StringBuilder sbErrMsg = null;
                acc.SavePlans(ndPlanInfos, ndPlanNameAssetInfos, maxAssetAmount, ref sbErrMsg);
                if (sbErrMsg.Length == 0)
                {
                    Alert.MessageBox("盘点计划已批量生成完毕");
                    acc.Commit();
                }
                else
                {
                    Alert.MessageBox(sbErrMsg.ToString());
                    acc.RollBack();
                }

            }
            catch (Exception ex)
            {
                acc.RollBack();
                throw ex;
            }
            finally
            {
                acc.CloseSession();
            }
            //CreatePlans(ref sbErrInfo);

            pgList.BindGrid();
        }
    }
}